package controller

import (
	"common"
	"context"
	"models/dal/query"
	"time"
	"user/internal/logic"
	"user/internal/pb"
)

type UserRegisterService struct {
	pb.UnimplementedUserServer
}

func (u *UserRegisterService) Register(ctx context.Context, req *pb.UserRegisterRequest) (*pb.UserRegisterResponse, error) {
	if err := logic.Register(req.Email, req.Password, req.NickName, req.Avatar); err != nil {
		return nil, err
	}
	return &pb.UserRegisterResponse{}, nil
}

func (u *UserRegisterService) Login(ctx context.Context, req *pb.UserLoginRequest) (*pb.UserLoginResponse, error) {
	return logic.Login(req.Email, req.Password)
}

func (u *UserRegisterService) Profile(ctx context.Context, req *pb.UserProfileRequest) (*pb.UserProfileResponse, error) {
	UserModel := query.Q.FaUser
	ctx, cancel := common.WithTimeoutContext(time.Second * 2)
	defer cancel()
	user, err := UserModel.WithContext(ctx).Where(UserModel.ID.Eq(req.UserId)).First()
	if err != nil {
		return nil, err
	}
	return &pb.UserProfileResponse{
		User: &pb.UserEntity{
			NickName: user.Nickname,
			Avatar:   user.Avatar,
		},
	}, nil
}

// EditProfile 修改用户资料
func (u *UserRegisterService) EditProfile(ctx context.Context, req *pb.EditProfileRequest) (*pb.EditProfileResponse, error) {
	if err := logic.EditProfile(req.UserId, req.NickName, req.Avatar); err != nil {
		return nil, err
	}
	return &pb.EditProfileResponse{}, nil
}
